var os = require('os');
var path = require('path');
var moment = require('moment');
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var FileStore = require('session-file-store')(session);
var uploaderConfig = { uploadDir: path.join(__dirname, 'public', 'uploads'), limitExtension: null };
var favicon = require('serve-favicon');
var config = require('./config');
var morgan = require('morgan');
var router = express.Router();
var fs = require('fs');
var log = console.log;
var app = express();

app.set('views', './views');
app.set('view engine', 'pug');
app.locals.pretty = config.pretty;

//生产环境中将模版缓存
if (app.get('env') === 'production') {
	app.set('view cache', true);
}

// 静态资源请求路径
app.use(express.static(path.join(__dirname, config.path)));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

morgan.token('params', function (req, res) {
	return JSON.stringify(req.params);
});

morgan.token('body', function (req, res) {
	return JSON.stringify(req.body);
});

morgan.token('time', function (req, res) {
	return moment((new Date).getTime()).format('hh:mm:ss');
});

//在 node 命令行中显示日志
if (os.type() == 'Windows_NT') {
	//windows...
	app.use(morgan(':time url::url :status ~:method params::params body::body'));							// :response-time ms
} else {
	//mac 及其他系统
	app.use(morgan(':time \033[36murl::url\033[39m \033[90m:status\033[39m ~\033[0m\033[1m\033[32m:method\033[0m\033[39m \033[34mparams:\033[39m\033[33m:params\033[39m \033[34mbody:\033[39m\033[33m:body\033[39m'));
}

//body-parser 解析json格式数据
app.use(bodyParser.json({ limit: '3mb' }));
//此项必须在 bodyParser.json 下面,为参数编码
app.use(bodyParser.urlencoded({
	extended: true
}));

app.use(session({
	name:'keydone',
	resave: false,										  // 是否每次都重新保存会话，建议false
  secret: 'keydone',									// 用来对session id相关的cookie进行签名
	cookie: {maxAge: 1000 * 60 * 60 * 12},						// 设置cookie有效期
	saveUninitialized: false,						// 是否自动保存未初始化的会话，建议false
	store: new FileStore()							// 本地存储session（文本文件，也可以选择其他store，比如redis等）
}));

app.listen(config.port);

if (os.type() == 'Windows_NT') {
	//windows...
	log("\033[1m--------\033[39m \033[32m服务器已启动,端口是\033[39m \033[33m" +config.port+ "\033[39m --------\033[39m\033[0m");
} else {
	//mac 及其他系统
	log("\033[31m--------\033[39m \033[32m服务器已启动,端口是\033[39m \033[33m" +config.port+ "\033[39m \033[31m--------\033[39m");
}

require('./router')(app)

// 创建上传的文件夹
if(!fs.existsSync('public/files/')){  
	fs.mkdirSync('public/files/');
}

// 捕获 404 并进行错误处理
app.use(function (req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
	app.set('showStackError', true);
	app.use(morgan('\033[32m:method\033[39m \033[36m:url\033[39m \033[90m[:status]\033[39m :response-time ms'));
	app.use(function (err, req, res, next) {
		res.status(err.status || 500);
		if (err.status == 404) {
			res.render('error', {
				error: err,
				status:404
			});
		} else {
			res.render('error', {
				message: err.message,
				error: err
			});
		}
	});
}

module.exports = app;